import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { PointRuleRewardType, PointRuleType, PointsRulesEntity } from './points-rules.entity';
import { Repository } from 'typeorm';
import { CreatePointsRulesDto, UpdatePointsRulesDto } from './points-rules.dto';

@Injectable()
export class PointsRulesService {
  constructor(
    @InjectRepository(PointsRulesEntity)
    private readonly pointsRulesRepo: Repository<PointsRulesEntity>
  ) {}

  async create(dto: CreatePointsRulesDto): Promise<PointsRulesEntity> {
    return await this.pointsRulesRepo.save(dto);
  }

  async update(id: number, dto: UpdatePointsRulesDto): Promise<PointsRulesEntity> {
    const existingRule = await this.pointsRulesRepo.findOne({ where: { id } });
    if (!existingRule) {
      throw new Error('积分规则不存在');
    }

    // 只更新传入的字段
    const updateData = {};
    if (dto.ruleName !== undefined) updateData['ruleName'] = dto.ruleName;
    if (dto.description !== undefined) updateData['description'] = dto.description;
    if (dto.targetCount !== undefined) updateData['targetCount'] = dto.targetCount;
    if (dto.fixedPoints !== undefined) updateData['fixedPoints'] = dto.fixedPoints;

    await this.pointsRulesRepo.update({ id }, updateData);
    return await this.pointsRulesRepo.findOne({ where: { id } });
  }

  async findAll(): Promise<PointsRulesEntity[]> {
    return await this.pointsRulesRepo.find({
      order: {
        createdAt: 'DESC',
      },
    });
  }

  async calcPointsByRule(rule: PointsRulesEntity, curCount: number): Promise<number> {
    switch (rule.ruleType) {
      case PointRuleType.FIXED: {
        switch (rule.rewardType) {
          case PointRuleRewardType.PER_ATTEMPT: {
            return rule.fixedPoints;
          }
          case PointRuleRewardType.FULL_COMPLETION: {
            if (Number(curCount) === rule.targetCount) {
              return rule.fixedPoints;
            } else {
              return 0;
            }
          }
        }
        break;
      }
      case PointRuleType.MULTIPLIER: {
				// TODO : 计算倍率积分
        break;
      }
      case PointRuleType.TIERED: {
				// TODO : 计算阶梯积分
        break;
      }
      case PointRuleType.TIME_BASED: {
				// TODO : 计算时间加成积分
        break;
      }
      case PointRuleType.RANDOM: {
				// TODO : 计算随机积分
        break;
      }
    }
  }
}
